using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.IO;
using System.Windows.Forms;

using Verety.SharedMeta.MessagingServiceMeta.Contacts;

using Verety.SharedMeta.DirectoryServiceMeta;
using Verety.SharedMeta.DirectoryServiceMeta.Conversation;
using SBPweb.Modules.Modularity;

namespace SBPweb.Modules.ChatController.History
{
	public class ChatHistoryManager
	{
		private static Hashtable chatHistoryList = new Hashtable();
		private static string historyPath;
		private static IDirectoryService mDirectoryService;

		private ChatHistoryManager()
		{
		}
		static ChatHistoryManager()
		{
			string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
			historyPath = Path.Combine(Path.Combine(appDataPath, "Verety"), Application.ProductName);
		}

		public static string HistoryPath
		{
			get
			{
				return historyPath;
			}
			set
			{
				historyPath = value;
			}
		}

		public static IDirectoryService DirectoryService
		{
			get
			{
				return DirectoryService;
			}
			set
			{
				mDirectoryService = value;
			}
		}

		public static ChatHistory CreateHistory(IContactId from, IContactId to, string routeAddress, IModule parentModule)
		{
			string key = createKey(from, to, routeAddress);
			ChatHistory chatHistory = new ChatHistory(mDirectoryService.Conversations as IDirectoryConversationManager, from, to, routeAddress, historyPath, parentModule);
			chatHistoryList.Add(key, chatHistory);

			return chatHistory;
		}

		public static bool CloseHistory(ChatHistory chatHistory)
		{
			string removeKey = null; ;

			foreach (string key in chatHistoryList.Keys)
			{
				if ((chatHistoryList[key] as ChatHistory).Equals(chatHistory))
				{
					removeKey = key;
				}
			}
			if (removeKey == null)
				return false;
			else
			{
				chatHistoryList.Remove(removeKey);
				chatHistory.Finalize();
				return true;
			}
		}

		public static ChatHistory GetChatHistory(string key)
		{
			return (ChatHistory)chatHistoryList[key];
		}

		public static ChatHistory GetChatHistory(IContactId from, IContactId to, string routeAddress)
		{
			string key = createKey(from, to, routeAddress);
			if ((ChatHistory)chatHistoryList[key] == null)
			{
				key = createKey(to, from, routeAddress);
			}
			return (ChatHistory)chatHistoryList[key];
			
		}

		private static string createKey(IContactId from, IContactId to, string routeAddress)
		{
			return (mDirectoryService.Conversations as IDirectoryConversationManager).GetBareJId(from) + "_" + (mDirectoryService.Conversations as IDirectoryConversationManager).GetBareJId(to) + "_" + routeAddress;
		}
	}
}
